#include "player.h"
#include "GameSetting.h"
#include "enemy.h"
#include "bullet.h"
#include <QGraphicsScene>
#include <QPixmap>
#include <QKeyEvent>
#include "health.h"
#include <QGraphicsTextItem>
#include <QFontMetrics>
#include "score.h"

using namespace GameSetting;
Player::Player(QGraphicsItem *parent):QGraphicsPixmapItem(parent) {
    bulletSound.setSource(QUrl("qrc:/sounds/bullet.wav"));
    setPixmap(QPixmap(":/image/Plane_1.png"));
    //缩放
    setScale(PlayerScale);
    //位置
    setPos(SceneWidth/2-boundingRect().width()*PlayerScale/2,
           SceneHeight-boundingRect().height()*PlayerScale);
    //可以获取焦点   并获取焦点
    setFlag(QGraphicsItem::ItemIsFocusable);
    setFocus();
    startTimer(1000);//半秒钟  触发一次

}


void Player::keyPressEvent(QKeyEvent *event)
{
    switch(event->key()){
        case Qt::Key_Left:
            if(pos().x()>0){
                setPos(x()-PlayerMoveSpeed,y());
            }
            break;

        case Qt::Key_Right:
            if(pos().x()<(SceneWidth-boundingRect().width()*PlayerScale)){
                setPos(x()+PlayerMoveSpeed,y());
            }
            break;
        case Qt::Key_S:
            if(playing) return;
            playing=true;
            Health::getInstance().reset();
            Score::getInstance().reset();
            messageItem->hide();
            break;
        case Qt::Key_Space:
            bulletSound.play();
            Bullet *bullet = new Bullet;
            //飞机中点坐标(只考虑player位置)
            int temp = x() +boundingRect().width()*PlayerScale/2;
            //子弹中心(向左移半个子弹宽度)
            temp -=bullet->boundingRect().width()*BulletScale/2;
            bullet->setPos(temp,y());
            scene()->addItem(bullet);
            //播放音效
            break;
    }
}

void Player::enemySpawn()
{
        Enemy *enemy = new Enemy;
        scene()->addItem(enemy);
}

void Player::gameOver()
{
    playing = false;
    for(auto item:scene()->items()){
        if(typeid(*item)==typeid(Enemy)){
            scene()->removeItem(item);
            delete item;
        }
    }
    if(!messageItem){
        messageItem  = new QGraphicsTextItem;
        scene()->addItem(messageItem);
        QString message("Game Over!按s健重新开始");
        messageItem->setPlainText(message);
        messageItem->setDefaultTextColor(Qt::red);
        QFont font(QFont("Courier New",GameSetting::FontSize*2,QFont::Bold));
        messageItem->setFont(font);
        QFontMetrics fm(font);
        int msgWidth = fm.horizontalAdvance(message);
        messageItem->setPos(SceneWidth/2-msgWidth/2,
                            SceneHeight/2);
    }else{
        messageItem->show();
    }
}

// QObject中的timerEvent事件重载-QObject定时器
void Player::timerEvent(QTimerEvent *event)
{
    if(playing){
        enemySpawn();
    }
    if(Health::getInstance().getHealth()<=0){
        gameOver();
    }
}
